//
//  RecSearchViewController.m
//  TravelEveryDay
//
//  Created by dlios on 15-10-21.
//  Copyright (c) 2015年 com.lanou3g. All rights reserved.
//

#import "RecSearchViewController.h"
#import "RecSearchTableViewCell.h"
#import "RecSearchModel.h"
#import "RecTravelNotesDetailsViewController.h"
#import "RecSearchCollectionViewCell.h"
@interface RecSearchViewController ()<UITableViewDataSource, UITableViewDelegate,UISearchBarDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

@end

@implementation RecSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:251/255. green:246/255. blue:233/255. alpha:1];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _dataArray = [[NSMutableArray alloc] init];
    
    [self setUpPage];
    [self setUpCollection];
    [self creatSearch];
    [_table reloadData];
    [self addFooter];
    
}
#pragma mark - 创建tableview
-(void)setUpPage
{
    _table = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 114) style:UITableViewStylePlain];
    _table.delegate = self;
    _table.dataSource = self;
    _table.separatorColor = [UIColor clearColor];
    [self.view addSubview:_table];
    
}
#pragma mark - 热门城市collectionview创建
-(void)setUpCollection
{
    _myView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:_myView];
    _myView.backgroundColor = [UIColor colorWithRed:251/255. green:246/255. blue:233/255. alpha:1];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10 * WIDTH, 60 * HEIGHT, SCREEN_WIDTH - 20 * WIDTH, 1)];
    lineView.backgroundColor = [UIColor colorWithRed:62/255 green:176/255. blue:193/255. alpha:1];
    [_myView addSubview:lineView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20 * WIDTH, 20 * HEIGHT, 150 * WIDTH, 40 * HEIGHT)];
    label.text = @"热门目的地";
    label.textColor = [UIColor colorWithRed:62/255 green:176/255. blue:193/255. alpha:1];
    label.font = [UIFont boldSystemFontOfSize:22.];
    [_myView addSubview:label];
    
    
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(110 * WIDTH, 30 * HEIGHT);
    flow.minimumInteritemSpacing = 10 * HEIGHT;
    flow.minimumLineSpacing = 10 * HEIGHT;
    flow.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    //热门目的地view创建
    UICollectionView *collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 70 * HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:flow];
    collection.backgroundColor = [UIColor colorWithRed:251/255. green:246/255. blue:233/255. alpha:1];
    collection.delegate = self;
    collection.dataSource = self;
    [collection registerClass:[RecSearchCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
    [_myView addSubview:collection];
    
}
#pragma mark - 创建搜索
-(void)creatSearch
{
    _mySearch = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 300 * WIDTH, 30 * HEIGHT)];
    [_mySearch setBarTintColor:[UIColor colorWithRed:39/255. green:140/255. blue:155/255. alpha:1]];
    [_mySearch sizeToFit];
    _mySearch.delegate = self;
    [_mySearch setPlaceholder:@"搜索国家、城市、景区、游记名"];
    
    self.navigationItem.titleView = _mySearch;
}
#pragma mark - search 点击
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_mySearch resignFirstResponder];
    
    [self getData:0 upOrDown:nil searchText:searchBar.text];
    //点击后热门城市view从主视图移除
    [_myView removeFromSuperview];
    [_dataArray removeAllObjects];
    [_table reloadData];
    
}
#pragma mark - tableview Delegate & Datasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 170 * HEIGHT;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecSearchModel *model = [_dataArray objectAtIndex:indexPath.row];
    static NSString *cellID = @"cell";
    RecSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[RecSearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.backgroundColor = [UIColor colorWithRed:251/255. green:246/255. blue:233/255. alpha:1];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //搜索关键字高亮
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:model.name];
    NSRange range = [model.name rangeOfString:_mySearch.text];
    [attr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    cell.titleLabel.attributedText = attr;
    [cell getData:model];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecSearchModel *model = [_dataArray objectAtIndex:indexPath.row];
    RecTravelNotesDetailsViewController *travel = [[RecTravelNotesDetailsViewController alloc] init];
    [self.navigationController pushViewController:travel animated:YES];
    travel.myId = model.myId;
}
#pragma mark - 刷新加载
-(void)addHeader
{
    __block RecSearchViewController *rec = self;
    [_table addLegendHeaderWithRefreshingBlock:^{
        rec.upOrDown = NO;
        [rec getData:0 upOrDown:rec.upOrDown searchText:rec.mySearch.text];
    }];
    [_table.header beginRefreshing];
}
-(void)addFooter
{
    __block RecSearchViewController *rec = self;
    [_table addLegendFooterWithRefreshingBlock:^{
        //第一天刷新page + 30
        rec.page = rec.page + 30;
        rec.upOrDown = YES;
        if (rec.page <= 30) {
            [rec getData:rec.page upOrDown:rec.upOrDown searchText:rec.mySearch.text];
        }
        if (rec.page > 30) {
            //第二天刷新page + 20
            [rec getData:rec.page - 10 upOrDown:rec.upOrDown searchText:rec.mySearch.text];
        }
    }];
}
#pragma mark - 数据获取
-(void)getData:(NSInteger)number upOrDown:(BOOL)upOrDown searchText:(NSString *)text
{
    [Refresh getdataWithString:[NSString stringWithFormat:@"http://api.breadtrip.com/search/?key=%@&start=%ld&count=20",text,number] block:^(id block) {
    
        for (NSDictionary *dic in [block objectForKey:@"trips"]) {
            RecSearchModel *model = [RecSearchModel modelWithDictionary:dic];
            [_dataArray addObject:model];
        }
        if (_dataArray.count == 0) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 100)];
            label.text = @"没有您搜索的资源";
            label.center = self.view.center;
            [self.view addSubview:label];
        }
        
        [_table.footer endRefreshing];
        [_table reloadData];
       
    }];
}
#pragma mark - search 点击方法
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    return YES;
}
-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar endEditing:YES];
}
#pragma mark - collectionView Delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 23;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    _cityArr = @[@"泰国",@"韩国",@"日本",@"法国",@"美国",@"意大利",@"马来西亚",@"英国",@"新加坡",@"希腊",@"瑞士",@"德国",@"台湾",@"香港",@"厦门",@"北京",@"丽江",@"成都",@"上海",@"拉萨",@"西安",@"大理",@"三亚"];
    RecSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
    cell.label.text = [_cityArr objectAtIndex:indexPath.row];
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    _mySearch.text = _cityArr[indexPath.row];
    
    //调用搜索点击方法
    [self searchBarSearchButtonClicked:_mySearch];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
